package com.asnike.P.bejeweled{
	import flash.events.MouseEvent;

	public class GameControl{
		
		include 'control/selectJewel.as';
		include 'control/checkJewel.as';
		include 'control/fillJewel.as';
		include 'control/controlTest.as';
		
		private var _model:GameModel;
		private var _view:GameView;
		
		public function GameControl( $model:GameModel, $view:GameView ){
			if( $model === null ){
				throw new TypeError( '$model은 null이 올 수 없습니다.' );
			}
			if( $view === null ){
				throw new TypeError( '$view은 null이 올 수 없습니다.' );
			}
			
			_model = $model;
			_view = $view;
			_view.init( _model.jewelRemoveDuration, _model.jewelShiftDuration, _model.jewelSelectEffect );
		}
		
		public function setJewelSize( $width:int, $height:int ):void{
			if( $width < 0 || $height < 0 ){
				throw new RangeError( '$width, $height 파라미터엔 음수가 올 수 없습니다.' );
			}
			
			_model.setJewelSize( $width, $height );
		}
		
		public function gameReady():void{
			_view.initTitle( btnStartClick );
		}
		private function btnStartClick():void{
			_view.hideTitle();
			setJewels();
		}
		private function setJewels():void{
			var i:int, j:int, k:int, l:int, map:Array, jewel:Jewel;
			
			map = getMap();
			for( i = 0, j = map.length ; i < j ; ++i ){
				for( k = 0, l = map[i].length ; k < l ; ++k ){
					jewel = getMovingJewel( map[i][k], Jewel.WIDTH*k + Jewel.WIDTH*.5, Jewel.HEIGHT*( i-5 ) + Jewel.HEIGHT*.5, 5, JEWEL_CLICK, ( i + 1 === j && k + 1 === l ) );
					map[i][k] = jewel;
				}
			}
			
			debugMap();
		}
		private function getMap():Array{
			return _model.getJewelMap();
		}
		private function getJewel( $type:int, $x:Number, $y:Number, $clickFunction:Function ):Jewel{
			var jewel:Jewel;
			
			jewel = _view.addJewel( $type, $x, $y );
			jewel.addEventListener( MouseEvent.CLICK, $clickFunction );
			
			return jewel;
		}
		private function getMovingJewel( $type:int, $x:Number, $y:Number, $moveAmount:int, $clickFunction:Function, $isLast:Boolean ):Jewel{
			var jewel:Jewel;
			
			jewel = getJewel( $type, $x, $y, $clickFunction );
			moveDownToJewel( jewel, $moveAmount, getEndFunction( $isLast ) );
			
			return jewel;
		}
		private function getEndFunction( $isLast:Boolean ):Function{
			if( $isLast ){
				return checkSameJewelsOneLine;
			}
			return null;
		}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	}
}